﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;

namespace SumPower.MailAccount.Web.Code
{
    public class MailAccount
    {
        public static bool Authenticate(string username, string password, string server, int port = 25)
        {
            using (TcpClient tcpConnection = new TcpClient(server, port))
            {
                try
                {
                    NetworkStream stream = tcpConnection.GetStream();
                    MailStream mailStream = new MailStream(stream);
                    //验证连接
                    mailStream.ReadResponse();
                    mailStream.CheckForStatusCode(220);

                    mailStream.WriteHelo(Dns.GetHostName());

                    mailStream.WriteAuthLogin();

                    mailStream.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(username)));
                    mailStream.ReadResponse();
                    mailStream.CheckForStatusCode(334);

                    mailStream.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(password)));
                    mailStream.ReadResponse();
                    mailStream.CheckForStatusCode(235);

                     return true;
                }
                catch(Exception){
                    return false;
                }

            }
        }
    }
}